import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/department_tree_entity.dart';
import 'package:safetymonitor/app/data/entities/application/department_user_entity.dart';

class PersonnelDepartmentTreeController extends GetxController {
  /// 页面标题
  String title = '';

  String type = '';

  /// 组织数据
  List<DepartmentTreeEntity> departmentTreeList = [];

  /// 是否为单选
  bool isRadio = true;

  /// 当前选中的人员数据
  List<DepartmentUserEntity> selectedUserList = [];
  ///  外部选择的人员数据
  List<DepartmentUserEntity> selectedUserListOutside = [];
  ///  树下所有的人
  List<DepartmentUserEntity> userListAll = [];

  /// 查询组织接口
  String? organizationalInterface;

  /// 查询人员接口
  String? personnelInterface;

  @override
  void onInit() {
    super.onInit();
    final Map<String, dynamic> arguments = Get.arguments as Map<String, dynamic>;
    try {
      // 获取标题
      title = arguments['title'] as String;
      selectedUserListOutside = arguments['initData'] as   List<DepartmentUserEntity>;
      // 获取类型
      type = arguments['type'] as String;
      if (arguments['isRadio'] != null) {
        // 是否单选
        isRadio = arguments['isRadio'] as bool;
      }
      if (arguments['organizationalInterface'] != null && arguments['organizationalInterface'] is String) {
        // 查询组织接口
        organizationalInterface = arguments['organizationalInterface'] as String;
      }
      if (arguments['personnelInterface'] != null && arguments['personnelInterface'] is String) {
        // 查询人员接口
        personnelInterface = arguments['personnelInterface'] as String;
      }
    } catch (e) {
      if (arguments['isRadio'] != null) {
        // 是否单选
        isRadio = arguments['isRadio'] as bool;
      }
      AppLogger.printLog(e.toString());
    }
    // 初始化数据
    initData();
  }

  Future<void> initData() async {
    SmartDialog.showLoading(backType: SmartBackType.block, msg: '加载中...');
    //获取所有组织数据
    final res =
        await HttpUtil().generateGetRequest<List<DepartmentTreeEntity>>(organizationalInterface ?? Interface.getDeptTree, queryParameters: {'parentId': UserManager.getUserCompanyId()}).execute();
    res.onSuccess((result) async {
      if (result.data != null && result.data!.isNotEmpty) {
        departmentTreeList = result.data!;
        // 使用 async/await 顺序执行
        await traverseAndAssignUserListAllOne(departmentTreeList);
        await traverseAndAssignUserListAllTwo(departmentTreeList);
        await traverseAndAssignUserListAllThree(departmentTreeList);
        update();
        SmartDialog.dismiss();
      }
      res.onError( (error) {
        SmartDialog.dismiss();
      });
    });
  }

  /// 点击组织节点
  Future<void> clickOnNode(DepartmentTreeEntity treeEntity, int level) async {
    treeEntity.isExpand = !treeEntity.isExpand!;
    // 展开状态且节点人员为空调用接口查询人员
    // if (treeEntity.isExpand! && treeEntity.userList!.isEmpty
    //     // && treeEntity.id != '100'
    //     ) {
    //   final userList = await getUserByTypeAndBDepart(treeEntity);
    //   treeEntity.userList!.addAll(userList);
      update();
    // } else {
    //   update();
    // }
  }

  /// 获取组织人员
  Future<List<DepartmentUserEntity>> getUserByTypeAndBDepart(DepartmentTreeEntity treeEntity) async {
    final List<DepartmentUserEntity> userList = [];
    //获取组织人员数据
    final res = await HttpUtil().generateGetRequest<List<DepartmentUserEntity>>(
      personnelInterface ?? Interface.getUserByDeptId,
      // queryParameters: {
      //   'deptId': treeEntity.id,
      //   'pageSize': 100,
      //   'pageNo': 1,
      // },
      queryParameters: {'parentId': treeEntity.id},
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        userList.addAll(result.data!);
      }
    });
    return userList;
  }

  /// 点击选择人员
  void selectPersonnel(DepartmentUserEntity user) {
    // 单选
    if (isRadio) {
      selectedUserList.clear();
      selectedUserList.add(user);
    } else {

      // 不包含相同id
      if (!selectedUserList.any((object) => object.id == user.id)) {
        selectedUserList.add(user);
      } else {
        selectedUserList.removeWhere((e)=>e.id == user.id);
      }

    }
    update();
  }

  /// 判断人员是否选中
  /// 返回 ture: 选中
  bool userIsSelected(DepartmentUserEntity user) {
    if (selectedUserList.any((object) => object.id == user.id)) {
      return true;
    }
    return false;
  }

  /// 完成
  void complete() {
    if (selectedUserList.isEmpty) {
      AppToast.showWarning('请选择人员!');
      return;
    }
    Get.back(result: selectedUserList);
  }

  bool isAll = false;

  /// 全选
  void isAllSelect() {
    isAll = !isAll;
    selectedUserList.clear();// 清空选中人员列表
    if (isAll) {
      SmartDialog.showLoading(backType: SmartBackType.block, msg: '加载中...');
    }
    //遍历departmentTreeList下的数据 向userList中添加数据（通过clickOnNode方法）
    // departmentTreeList.forEach((element) async {
    //   if (isAll) {
    //     final userList = await getUserByTypeAndBDepart(element);
    //     element.userList!.addAll(userList);
    //   } else {
    //     element.userList!.clear();
    //   }
    // });
    traverseAndAssignUserList(departmentTreeList).then((e) {
      update();
    });
    if (isAll) {
      //延迟3秒
      Future.delayed(const Duration(seconds: 3), SmartDialog.dismiss);
    }
  }

  /// 递归遍历树节点，并赋值给userList
  Future<void> traverseAndAssignUserList(List<DepartmentTreeEntity> nodes) async {
    for (var node in nodes) {
      // if (node.id != '100') {
      //移除主公司id
      // 如果有子节点，递归赋值
      //向userList中添加数据（通过clickOnNode方法）
      if (isAll) {
        node.isExpand = true;
        if (node.userList!.isEmpty) {
          final List<DepartmentUserEntity> userList = await getUserByTypeAndBDepart(node);
          //遍历 userList 向 selectPersonnel添加
          userList.forEach(selectPersonnel);
          node.userList!.addAll(userList);
        } else {
          node.userList!.forEach(selectPersonnel);
        }
      } else {
        // node.userList!.clear();
        selectedUserList.clear();
      }
      // }

      traverseAndAssignUserList(node.children!);
    }
  }

  List<DepartmentUserEntity> userList100 = [];

  /// 递归遍历树节点，并赋值给userList(获取100下的人员)
  Future<void> traverseAndAssignUserListAllOne(List<DepartmentTreeEntity> nodes) async {
    for (var node in nodes) {
      if (node.id == '100') {
        userList100 = await getUserByTypeAndBDepart(node);
        node.userList!.addAll(userList100);
        return;
      }
      await  traverseAndAssignUserListAllOne(node.children!);
    }
  }
  /// 递归遍历树节点，并赋值给userList(获取不是100下的人员)
  /// 过滤userList100下的相同人员和userList比对
  Future<void> traverseAndAssignUserListAllTwo(List<DepartmentTreeEntity> nodes) async {
    for (var node in nodes) {
      if (node.id != '100') {
        final List<DepartmentUserEntity> userList = await getUserByTypeAndBDepart(node);
        //把userList100种和userList相同的删除
        for (var node in userList) {
          userList100.removeWhere((e) => e.nickname == node.nickname);
        }
        node.userList!.addAll(userList);
        //设置每个节点的userList 给所有的人的集合
        userListAll.addAll(userList);
      }
      //初始化设置 之前选中的人
      //通过递归遍历整颗departmentTreeList树 给 selectedUserListOutside中选中的人 设置到树上
      if(selectedUserListOutside.isNotEmpty){
        selectedUserListOutside.forEach(selectPersonnel);
      }
      await  traverseAndAssignUserListAllTwo(node.children!);
    }
  }
  /// 把比对好的userList100下的人员赋值给100
  Future<void> traverseAndAssignUserListAllThree(List<DepartmentTreeEntity> nodes) async {
    for (var node in nodes) {
      if (node.id == '100') {
        node.userList = userList100;
        userListAll.addAll(userList100);
        // userListAll.  insertAll(0, userList100);
        //userListAll集合和selectedUserListOutside集合数量孩子是否一致
        isAll= userListAll.length == selectedUserList.length;
        return;
      }
     await traverseAndAssignUserListAllThree(node.children!);
    }
  }
}
